package com.wcy.controller;

import com.wcy.entity.Role;
import com.wcy.entity.User;
import com.wcy.entity.UserRole;
import com.wcy.feign.perm.FeignPermAuthService;
import com.wcy.feign.perm.FeignRoleService;
import com.wcy.feign.user.FeignAuthorizeService;
import com.wcy.util.JwtTokenUtil;
import com.wcy.util.Util;
import com.wcy.util.vo.AuthRequest;
import com.wcy.util.vo.AuthResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class AuthorizeController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private FeignAuthorizeService feignAuthorizeService;
    @Resource
    private FeignPermAuthService feignPermAuthService;
    @Resource
    private FeignRoleService feignRoleService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;


    @PostMapping("auth/login")
    public ResponseEntity<AuthResponse> login(@RequestBody AuthRequest authRequest) {
        authRequest.setRandomCode(Util.generateRandomCode(10));
        AuthResponse resp = feignAuthorizeService.login(authRequest).getBody();
        System.out.println(authRequest+" "+resp);
        assert resp != null;
        List<Object> args = new ArrayList<>();
        args.add(authRequest);
        args.add(resp);
        List<String> perms = feignPermAuthService.getPermissionsByRoleList(args).getBody();
        resp.setPerms(perms);
        if(perms!=null&&!perms.isEmpty())
            redisTemplate.opsForValue().set(resp.getToken(),String.join(",",perms));
        System.out.println(resp);
        return ResponseEntity.ok(resp);
    }

    @PostMapping("auth/register")
    public ResponseEntity<Void> register(@RequestBody User user) {
        System.out.println(user);
        List<Role> defaultRoles = feignRoleService.getDefault().getBody();
        assert defaultRoles != null;
        user.setRoles(defaultRoles.stream().map(e->new UserRole(e.getRoleId())).collect(Collectors.toList()));
        return feignAuthorizeService.register(user);
    }
    @PostMapping("auth/logout")
    public ResponseEntity<Void> logout(HttpServletRequest request) {
        String token = jwtTokenUtil.getToken(request);
        //移除Redis中token缓存
        redisTemplate.delete(token);
        return null;
    }
}
